<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { GroupApi } from '#/api/system/group';

const emit = defineEmits<{ select: [{ groups: string[]; id: string }] }>();
const pk = ref<string>('');
const gridOptions: VxeGridProps<GroupApi.GroupResult> = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
  },
  columns: [
    { align: 'left', type: 'checkbox', width: 60 },
    { field: 'name', title: '名称' },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) =>
        GroupApi.listGroup({
          page: page.currentPage,
          page_size: page.pageSize,
          ...formValues,
        }),
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  // formOptions,
  gridOptions,
});
const [Modal, modalApi] = useVbenModal({
  onOpened() {
    const data = modalApi.getData();
    pk.value = data.id;
    gridApi.grid.setCheckboxRowKey(
      data.groups.map((item: { id: string }) => item.id),
      true,
    );
  },
  async onConfirm() {
    const groups = gridApi.grid.getCheckboxRecords().map((item: { id: string }) => item.id);
    emit('select', { groups, id: pk.value });
  },
});
</script>

<template>
  <Modal title="选择用户组">
    <Grid />
  </Modal>
</template>
